package com.attendance.service.impl;

import com.attendance.mapper.*;
import com.attendance.model.*;
import com.attendance.service.IStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.*;

/**
 * Created by OPTIPLEX on 2016/12/13.
 */
@Service
public class StatsServiceImpl  implements IStatsService {


    @Autowired
    public EmployeeMapper employeeMapper;

    @Autowired
    public RecordMapper recordMapper;

    @Autowired
    public TypeMapper typeMapper;

    @Autowired
    ApplyMapper applyMapper;

    @Autowired
    VacationMapper vacationMapper;

    @Autowired
    DepartmentMapper departmentMapper;

    @Override
    public Stats getStatsByUid(Integer uid, Date startDate, Date endDate) {
        Stats stats = new Stats();
        stats.setId(this.employeeMapper.getEmployeeById(uid));

        List<Vacation> approvedApplyStats = new ArrayList<>();


        List<Type> types = this.typeMapper.getAll();
        for (Type t: types){


            List<Apply> approvedApplies = this.applyMapper.getApprovedApplyByIdAndType(7,t.getId(),ApplyState.APPROVED.getValue());
            Integer num = approvedApplies.size();

            Vacation v = new Vacation();

            v.setUid(uid);
            v.setType(t.getId());
            v.setNumber(num);
            v.setRest(0);

            if (t.getId() == 3){
                Vacation tmp = this.vacationMapper.getByUidAndType(uid, t.getId());
                if (tmp != null){
                    v = tmp;
                }
            }
            approvedApplyStats.add(v);

        }
        stats.setApprovedApplyNum(approvedApplyStats);


        stats.setRecords(this.recordMapper.getByUidAndDate(uid, startDate, endDate));


        System.out.println(stats.getRecords());
        stats.setNumWorkDay(stats.getRecords().size());
//for communication efficiency, do not transfer records
        stats.setRecords(null);

        return stats;
    }

    @Override
    public List<Stats> getStatsAll(Date startDate, Date endDate){
        List<Employee> employees = this.employeeMapper.getAllEmployee();
        List <Stats> result = new ArrayList<>();
        for(Employee e: employees){
            Stats stats = this.getStatsByUid(e.getId(),startDate,endDate);
            result.add(stats);
        }
        return result;
    }

    @Override
    public List<Stats> getStatsByDeptId(Integer deptId, Date startDate, Date endDate) {
        List<Employee> employees = this.employeeMapper.getEmployeeByDeptId(deptId);
        List<Stats> result = new ArrayList<>();
        for (Employee e : employees) {
            Stats stats = this.getStatsByUid(e.getId(), startDate, endDate);
            result.add(stats);
        }
        return result;
    }

}
